package com.xayoudao.uneng;

import java.util.ArrayList;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.xayoudao.uneng.api.APIManager;
import com.xayoudao.uneng.domain.MessageResult;
import com.xayoudao.uneng.domain.Subarea;
import com.xayoudao.uneng.util.SystemUiHider;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class MainActivity extends Activity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;

	private MapView mMapView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 获取应用
		UnengApplication app = (UnengApplication) this.getApplication();
		// 初始化地图管理
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(this);
			app.mBMapManager.init(UnengApplication.strKey,
					new UnengApplication.MyGeneralListener());
		}

		setContentView(R.layout.activity_main);
		// 获取地图View
		// final View controlsView =
		// findViewById(R.id.fullscreen_content_controls);
		mMapView = (MapView) findViewById(R.id.bmapView);

		initMapView();

		/**
		 * 设定地图中心点
		 */
		// GeoPoint p = new GeoPoint((int) (39.933859 * 1E6),
		// (int) (116.400191 * 1E6));
		// mMapView.getController().setCenter(p);

		this.location();

		this.initOverlay();

		/**
		 * 创建一个popupoverlay
		 */
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				Log.d("Main", "index == " + index);
			}
		};
		pop = new PopupOverlay(mMapView, popListener);

		// 全屏设置
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		mSystemUiHider = SystemUiHider.getInstance(this, mMapView, HIDER_FLAGS);
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							// if (mControlsHeight == 0) {
							// mControlsHeight = controlsView.getHeight();
							// }
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							// controlsView.animate()
							// .translationY(visible ? 0 : mControlsHeight)
							// .setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							// controlsView.setVisibility(visible ? View.VISIBLE
							// : View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(AUTO_HIDE_DELAY_MILLIS);
						}
					}
				});
	}

	// 定位相关
	LocationClient mLocClient;
	LocationData locData = null;
	public MyLocationListenner myListener = new MyLocationListenner();

	// 定位图层
	MyLocationOverlay myLocationOverlay = null;

	/**
	 * 定位自己的位置
	 */
	private void location() {
		// 定位初始化
		mLocClient = new LocationClient(this);
		locData = new LocationData();
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(5000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		// 定位图层初始化
		myLocationOverlay = new MyLocationOverlay(mMapView);

		myLocationOverlay.setLocationMode(LocationMode.NORMAL);
		// 设置定位数据
		myLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		// 修改定位数据后刷新图层生效
		mMapView.refresh();
	}

	private MyOverlay mOverlay = null;
	private PopupOverlay pop = null;

	/**
	 * 标注附近的校区
	 */
	public void initOverlay() {

		APIManager.getInstance().subarea(MainActivity.this, "", "",
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(JSONObject jsonObject) {
						super.onSuccess(jsonObject);
						MessageResult result = MessageResult.prase(jsonObject);
						if (result.success()) {
							Log.d("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",
									jsonObject.toString());

							ArrayList<Subarea> subarea = Subarea
									.parser(jsonObject.optJSONArray("data"));

							/**
							 * 创建自定义overlay
							 */
							mOverlay = new MyOverlay(getResources()
									.getDrawable(R.drawable.icon_marka),
									mMapView);
							/**
							 * 准备overlay 数据
							 */
							for (int i = 0; i < subarea.size(); i++) {
								Log.d("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",
										subarea.get(i).toString());

								GeoPoint p1 = new GeoPoint((int) (subarea
										.get(i).getLat() * 1E6), (int) (subarea
										.get(i).getLng() * 1E6));
								OverlayItem item = new OverlayItem(p1, "覆盖物1",
										"");
								/**
								 * 设置overlay图标，如不设置， 则使用创建ItemizedOverlay时的默认图标.
								 */
								item.setMarker(getResources().getDrawable(
										R.drawable.icon_marka));
								mOverlay.addItem(item);
							}
							/**
							 * 将overlay 添加至MapView中
							 */
							mMapView.getOverlays().add(mOverlay);

							/**
							 * 刷新地图
							 */
							mMapView.refresh();

							Toast.makeText(MainActivity.this, "loading ok",
									Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(MainActivity.this,
									result.getMessage(), Toast.LENGTH_SHORT)
									.show();
						}
					}

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						super.onFailure(arg0, arg1);
						// DeviceUtils.stopProgressDialog();
						Toast.makeText(MainActivity.this, "登录失败，请重试",
								Toast.LENGTH_SHORT).show();
					}
				});

	}

	/**
	 * 清除所有Overlay
	 * 
	 * @param view
	 */
	public void clearOverlay(View view) {
		mOverlay.removeAll();

		mMapView.refresh();
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		if (mLocClient != null)
			mLocClient.stop();
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	private void initMapView() {
		// mMapView.setLongClickable(true);
		// 当前的缩放级别
		mMapView.getController().setZoom(16);
		// 支持点击
		mMapView.getController().enableClick(true);
		//
		// // 是否启用缩放手势
		mMapView.getController().setZoomGesturesEnabled(true);
		// // 是否启用平移手势
		mMapView.getController().setScrollGesturesEnabled(true);
		// // 是否启用双击放大
		mMapView.setDoubleClickZooming(true);
		// // 是否显示内置绽放控件
		mMapView.setBuiltInZoomControls(true);
		// // 是否启用俯视手势
		mMapView.getController().setOverlookingGesturesEnabled(false);
		// // 是否启用旋转手势
		mMapView.getController().setRotationGesturesEnabled(false);

	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}

	public class MyOverlay extends ItemizedOverlay {

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}

		@Override
		public boolean onTap(int index) {
			OverlayItem item = getItem(index);

			pop.showPopup(BitmapFactory.decodeResource(getResources(),
					R.drawable.bg_fri_box), item.getPoint(), 32);

			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView) {
			if (pop != null) {
				pop.hidePop();
//				mMapView.removeView(button);
			}
			return false;
		}

	}

	boolean isFirstLoc = true;// 是否首次定位

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			// 更新定位数据
			myLocationOverlay.setData(locData);
			// 更新图层数据执行刷新后生效
			mMapView.refresh();
			// 是手动触发请求或首次定位时，移动到定位点

			// 移动地图到定位点
			if (isFirstLoc) {
				Log.d("LocationOverlay", "receive location, animate to it");
				mMapView.getController().animateTo(
						new GeoPoint((int) (locData.latitude * 1e6),
								(int) (locData.longitude * 1e6)));

				// myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
			}
			// 首次定位完成
			isFirstLoc = false;
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

}
